<?php

namespace app\api\controller;

use app\common\basic\BaseController;
use app\common\model\CrmCustomerAttachment;
use app\common\model\CrmCustomers;
use app\common\model\CrmFollowUps;
use support\Request;
use Carbon\Carbon;

class IndexController extends BaseController
{
    public function dashboard(Request $request)
    {
        // 获取时间范围参数，默认为当月
        $timeRange = $request->get('time_range', 'this_month');
        $dateRange = $this->getDateRange($timeRange);
        
        // 客户统计
        $statistics = [
            'time_range' => [
                'today' => '今天',
                'yesterday' => '昨天',
                'this_week' => '本周',
                'last_week' => '上周',
                'this_month' => '本月',
                'last_month' => '上月',
                'this_quarter' => '本季度',
                'last_quarter' => '上季度',
                'this_year' => '本年',
                'last_year' => '去年',
            ],
            'date_range' => [
                'start' => $dateRange['start']->toDateTimeString(),
                'end' => $dateRange['end']->toDateTimeString()
            ],
            'statistics' => $this->getCustomerStatistics($dateRange),
        ];
        
        return $this->success($statistics);
    }
    
    /**
     * 获取日期范围
     */
    private function getDateRange($timeRange)
    {
        $now = Carbon::now();
        
        switch ($timeRange) {
            case 'today':
                return [
                    'start' => $now->copy()->startOfDay(),
                    'end' => $now->copy()->endOfDay()
                ];
            case 'yesterday':
                return [
                    'start' => $now->copy()->subDay()->startOfDay(),
                    'end' => $now->copy()->subDay()->endOfDay()
                ];
            case 'this_week':
                return [
                    'start' => $now->copy()->startOfWeek(),
                    'end' => $now->copy()->endOfWeek()
                ];
            case 'last_week':
                return [
                    'start' => $now->copy()->subWeek()->startOfWeek(),
                    'end' => $now->copy()->subWeek()->endOfWeek()
                ];
            case 'this_month':
                return [
                    'start' => $now->copy()->startOfMonth(),
                    'end' => $now->copy()->endOfMonth()
                ];
            case 'last_month':
                return [
                    'start' => $now->copy()->subMonth()->startOfMonth(),
                    'end' => $now->copy()->subMonth()->endOfMonth()
                ];
            case 'this_quarter':
                return [
                    'start' => $now->copy()->startOfQuarter(),
                    'end' => $now->copy()->endOfQuarter()
                ];
            case 'last_quarter':
                return [
                    'start' => $now->copy()->subQuarter()->startOfQuarter(),
                    'end' => $now->copy()->subQuarter()->endOfQuarter()
                ];
            case 'this_year':
                return [
                    'start' => $now->copy()->startOfYear(),
                    'end' => $now->copy()->endOfYear()
                ];
            case 'last_year':
                return [
                    'start' => $now->copy()->subYear()->startOfYear(),
                    'end' => $now->copy()->subYear()->endOfYear()
                ];
            default:
                return [
                    'start' => $now->copy()->startOfMonth(),
                    'end' => $now->copy()->endOfMonth()
                ];
        }
    }
    
    /**
     * 获取客户统计数据
     */
    private function getCustomerStatistics($dateRange)
    {
        $startDate = $dateRange['start']->toDateTimeString();
        $endDate = $dateRange['end']->toDateTimeString();
        $uid = request()->user['id'] ?? 0;
        // 新增客户数
        $newCustomers = CrmCustomers::where('user_id', $uid)->whereBetween('create_time', [$startDate, $endDate])
            ->count();
            
        // 跟进客户数 - 跟进时间在范围内
        $followedCustomers = CrmCustomers::where('user_id', $uid)->whereBetween('follow_up_time', [$startDate, $endDate])->where('stage', 2)->count();
            
        // 签约客户数 - 上传附件即认为签约
        $signedCustomers = CrmCustomers::where('user_id', $uid)->whereBetween('sign_time', [$startDate, $endDate])->where('stage', 3)->count();
        
        // 待跟进客户数 - 新增客户但未跟进
        $pendingFollowUpCustomers = CrmCustomers::where('user_id', $uid)->whereBetween('create_time', [$startDate, $endDate])->where('stage', 1)->count();

        // 转化率 = 签约客户数 / 跟进客户数;
        $conversionRate = $followedCustomers > 0 ? bcmul(bcdiv($signedCustomers, $followedCustomers, 4), 100, 2) : 0;

        //客户签约占比：签约客户/新增客户*100%
        $signedCustomerRatio = $newCustomers > 0 ? bcmul(bcdiv($signedCustomers, $newCustomers, 4), 100, 2) : 0;
        //客户跟进占比：跟进客户/新增客户*100%
        $followedCustomerRatio = $newCustomers > 0 ? bcmul(bcdiv($followedCustomers, $newCustomers, 4), 100, 2) : 0;
        
        return [
            // 新增客户数
            'new_customers' => $newCustomers,
            // 跟进客户数
            'followed_customers' => $followedCustomers,
            // 签约客户数
            'signed_customers' => $signedCustomers,
            // 待跟进客户数
            'pending_followup_customers' => $pendingFollowUpCustomers,
            // 总客户数
            'total_customers' => CrmCustomers::where('user_id', $uid)->count(),
            // 转化率
            'conversion_rate' => $conversionRate,
            // 客户签约占比
            'signed_customer_ratio' => $signedCustomerRatio,
            // 客户跟进占比
            'followed_customer_ratio' => $followedCustomerRatio,
        ];
    }
}